import { getToken, setToken, removeToken } from '@/utils/auth'
import { login ,getUserInfo} from '@/api/user'

const state = {
  token: getToken(), // 从缓存中读取初始值
  userInfo:'',
}
const mutations = {
  setToken(state, token) {
    state.token = token
    // 同步到缓存
    setToken(token)
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  removeToken(state) {
    // 删除Vuex的token
    state.token = null
    removeToken()
  }
}
const actions = {
  async login(context, data) {
    const { mobile, password } = data
    // 调用登录接口
    const token = await login({ mobile, password })
    // 存入token
    context.commit('setToken', token)
  },

  async logout(context) {
    // 删除token
    context.commit('removeToken')
  },
  async getUserInfo(context) {
    const res = await getUserInfo()
    context.commit('setUserInfo', res)
  }
}

export default {
  namespaced: true, // 开启命名空间
  state,
  mutations,
  actions
}
